import datetime
import json
import math
import time
import zlib

from celery.utils.serialization import jsonify
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from future.backports.http.client import HTTPResponse

from app.config import server_config


class MiddlewareMixin(object):
    def __init__(self, get_response=None):
        self.get_response = get_response
        super(MiddlewareMixin, self).__init__()

    def __call__(self, request):
        response = None
        if hasattr(self, 'process_request'):
            response = self.process_request(request)
        if not response:
            response = self.get_response(request)
        if hasattr(self, 'process_response'):
            response = self.process_response(request, response)
        return response


class RbacMiddleware(MiddlewareMixin):
    """
    检查用户的url请求是否在其权限范围内
    """
    def process_request(self, request):
        remote_ip = request.META.get('REMOTE_ADDR')
        if server_config.get('is_ip_restrict') and remote_ip not in server_config.get('safe_ip'):
            return jsonify(code=403, success=False, msg=u"该IP无权限")
        path = request.path_info
        safe_url_flag = server_config.get('safe_url_flag')
        if not safe_url_flag:
            return jsonify(code=403, success=False,msg=u"url无权限")
        for item in safe_url_flag:
            if "login/" + item in path:
                return jsonify(code=403, success=False, msg=u"url invalid")
        return None


def datetime_handler(x):
    if isinstance(x, datetime.datetime):
        return int(time.mktime(x.timetuple()))
    return None


def jsonify(*args, **kwargs):
    """
    通用返回json
    """
    return HTTPResponse(
        json.dumps(dict(*args, **kwargs), ensure_ascii=False, default=datetime_handler),
        content_type="application/json;charset=utf-8"
    )


def dcompress(zstr):
    """
    字符串解压缩
    """
    if zstr:
        try:
            return zlib.decompress(zstr).strip()
        except Exception:
            return ""

    return ""


def isCharset(str, charset="utf-8"):
    """
    判断字符编码
    """
    return True


def humanReadadleDate(datetime):
    """
    通用日期格式化：datetime
    """
    if not datetime:
        return ""

    format = "%Y-%m-%d %H:%M:%S"
    return datetime.strftime(format)


def humanDate(datetime):
    """
    通用日期格式化：date
    """
    if not datetime:
        return ""

    format = "%Y-%m-%d"
    return datetime.strftime(format)


def pageslist(datas, num, page):
    """
    分页显示
    :param datas: 分页的所有数据， 列表格式
    :param num: 要展示的页数
    :param page: 每页展示的数量
    :return:
    """
    paginator = Paginator(list(datas), num) # num为每页显示的数量
    Totalcount = paginator.count # 获取记录数
    Totalpages = paginator.num_pages # 获取总页数
    try:
        contacts = paginator.page(int(page)).object_list # page为url中传入的页数
    except PageNotAnInteger:
        contacts = paginator.page(1).object_list
    except EmptyPage:
        contacts = paginator.page(paginator.num_pages).object_list
    data = {"Total": Totalcount, "Infos": contacts, "Totalpages": Totalpages}
    return data


def pages_limit_list(datas, total, nums):
    """
    django mysql limit分页
    :param datas:
    :param total:
    :param nums:
    :return:
    """
    total_pages = math.ceil(total / nums)
    info = {}

    info['Infos'] = list(datas)
    info['Total'] = total
    info['Totalpages'] = total_pages

    return info


